/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.snow.spring.mvc.processor.impl;

import cn.icanci.snow.spring.mvc.RequestProcessorChain;
import cn.icanci.snow.spring.mvc.processor.RequestProcessor;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;

/**
 * JPS 资源请求处理器
 *
 * @author icanci
 * @date Created in 2021/05/19 17:23
 * @version 1.0
 */
public class JspRequestProcessor implements RequestProcessor {

    /**
     * jsp请求的RequestDispatcher的名称
     */
    private static final String JSP_SERVLET         = "jsp";
    /**
     * Jsp请求资源路径前缀
     */
    private static final String JSP_RESOURCE_PREFIX = "/templates/";

    /**
     * jsp的RequestDispatcher,处理jsp资源
     */
    private RequestDispatcher   jspServlet;

    /**
     * 构造函数
     * @param servletContext RequestDispatcher
     */
    public JspRequestProcessor(ServletContext servletContext) {
        jspServlet = servletContext.getNamedDispatcher(JSP_SERVLET);
        if (null == jspServlet) {
            throw new RuntimeException("there is no jsp servlet");
        }
    }

    /**
     * jsp 处理器
     * @param requestProcessorChain 请求链
     * @return 返回是否继续执行
     * @throws Exception 异常
     */
    @Override
    public boolean process(RequestProcessorChain requestProcessorChain) throws Exception {
        if (isJspResource(requestProcessorChain.getRequestPath())) {
            jspServlet.forward(requestProcessorChain.getRequest(), requestProcessorChain.getResponse());
            return false;
        }
        return true;
    }

    /**
     * 是否请求的是jsp资源
     * @param url 请求路径
     * @return 是否是jsp资源
     */
    private boolean isJspResource(String url) {
        return url.startsWith(JSP_RESOURCE_PREFIX);
    }
}
